package com.zhaoyan.okgorxjavademo.activity;


import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.db.DownloadManager;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;
import com.zhaoyan.okgorxjavademo.Contacts;
import com.zhaoyan.okgorxjavademo.Contacts1;
import com.zhaoyan.okgorxjavademo.Login;
import com.zhaoyan.okgorxjavademo.LzyResponse;
import com.zhaoyan.okgorxjavademo.R;
import com.zhaoyan.okgorxjavademo.base.BaseActivity;
import com.zhaoyan.okgorxjavademo.injector.DaggerMainComponent;
import com.zhaoyan.okgorxjavademo.injector.MainModule;
import com.zhaoyan.okgorxjavademo.model.Main;
import com.zhaoyan.okgorxjavademo.presenter.MainPresenter;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends BaseActivity<MainPresenter> implements Main.View {


    @BindView(R.id.tv_start)
    TextView tvStart;
    @BindView(R.id.tv_pause)
    TextView tvPause;
    @BindView(R.id.tv_restart)
    TextView tvRestart;
    @BindView(R.id.tv_propress)
    TextView tvPropress;
    private static final int REQUEST_PERMISSION_STORAGE = 0x01;
    private String url = "http://119.167.155.242:8082/download/view/apk/huangjin/huangjin_v20.apk";
    private DownloadTask register;

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initEventAndData() {
//        mPresenter.getContacts("", "");
//        mPresenter.login();
//        mPresenter.getContacts1();

        OkDownload.getInstance().setFolder(Environment.getExternalStorageDirectory().getAbsolutePath() + "/aaa/");
        OkDownload.getInstance().getThreadPool().setCorePoolSize(3);
        String folder = OkDownload.getInstance().getFolder();
        //从数据库中恢复数据
        List<Progress> progressList = DownloadManager.getInstance().getAll();
        OkDownload.restore(progressList);


        checkSDCardPermission();
        //这里只是演示，表示请求可以传参，怎么传都行，和okgo使用方法一样
        GetRequest<File> request = OkGo.<File>get(url);//
//                        .headers("aaa", "111")//
//                        .params("bbb", "222");

        //这里第一个参数是tag，代表下载任务的唯一标识，传任意字符串都行，需要保证唯一,我这里用url作为了tag
        //
//                        .priority()//
//                        .extra1(apk)//
//
        register = OkDownload.request(url, request)//
//                        .priority()//
//                        .extra1(apk)//
                .save()//
                .register(new DownloadListener(url) {
                    @Override
                    public void onStart(Progress progress) {
                        Toast.makeText(MainActivity.this, "开始下载！", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onProgress(Progress progress) {
                        Toast.makeText(MainActivity.this, "下载中", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onError(Progress progress) {
                        Toast.makeText(MainActivity.this, "下载出错", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onFinish(File file, Progress progress) {
                        Toast.makeText(MainActivity.this, "下载完成", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onRemove(Progress progress) {
                        Toast.makeText(MainActivity.this, "移除下载", Toast.LENGTH_LONG).show();
                    }
                });
    }

    /**
     * 检查SD卡权限
     */
    protected void checkSDCardPermission() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_STORAGE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //获取权限
            } else {
                Toast.makeText(this, "权限被禁止，无法下载文件！", Toast.LENGTH_LONG).show();
            }
        }
    }

    @OnClick({R.id.tv_start, R.id.tv_pause, R.id.tv_restart})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_start:

                register.start();
                break;
            case R.id.tv_pause:
                register.pause();
                break;
            case R.id.tv_restart:
                register.restart();
                break;
        }
    }

    @Override
    public void getContacatsSuccess1(Contacts1 contacts) {
        Log.d("123", "getContacatsSuccess: " + contacts.toString());
        Toast.makeText(this, contacts.toString(), Toast.LENGTH_LONG).show();
    }

    @Override
    public void getContacatsSuccess(LzyResponse<List<Contacts>> contacts) {
        Log.d("123", "getContacatsSuccess: " + contacts.toString());
        Toast.makeText(this, contacts.toString(), Toast.LENGTH_LONG).show();
    }

    @Override
    public void loginSuccess(LzyResponse<Login> contacts) {
        Log.d("123", "getContacatsSuccess: " + contacts.toString());
        Toast.makeText(this, contacts.toString(), Toast.LENGTH_LONG).show();
    }

    @Override
    public void mainFail(Throwable throwable) {
        Log.d("123", "getContacatsSuccess:有问题 " + throwable.getMessage());
        Toast.makeText(this, "有问题" + throwable.getMessage(), Toast.LENGTH_LONG).show();
    }

    @Override
    protected void initInject() {
        DaggerMainComponent.builder().
                mainModule(new MainModule(this)).
                build().
                inject(this);
    }


}
